<?php

namespace app\api\controller\ai;

use think\facade\Cache;
use thinkct\controller\Frontend;
use thinkct\facade\ChatAI;
use GuzzleHttp\Client;
use orhanerday\OpenAi;
use app\common\model\ai\Message;

class Test extends Frontend
{
    private $last = '';
    protected $message_id = 2;

    protected array $noNeedLogin = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function index(): void
    {
        $this->success('hello world');
    }

    public function test(): void
    {
        // 发送对话
        ChatAI::sendText('php网站', '你现在是一个markdown语法专家，我需要用markmap制作思维导图，你需要把我提的要求转换成markdown的形式输出，请包括至少5个分支主题。同时，请为每个分支主题添加至少两个子主题，并在需要的情况下，为子主题添加更多层次的子主题，内容需要尽可能详细。在此过程中不要输出任何无关markdown语法的内容。之后的对话都按此要求进行。');
        //ChatAI::sendText('php获取百度首页', '你是一个万能助手');
    }

    public function ai2()
    {
        //             ob_flush();
        //            flush();
        //            return strlen($data);

        // 循环发送消息
        $message = '你好';

        for ($i = 0; $i < 10; $i++) {
            echo $message;
            ob_flush();
            flush();
            return strlen($message);
        }
    }

    public function ai()
    {
        $open_ai = new OpenAi('sk-O6LofAEvZHPNh1YP4803FeD69aC64b93B58e30A344A25c66');

        $open_ai->setBaseURL('https://api.ae76.cn');

        $chat = $open_ai->chat([
            'model' => 'gpt-4-all',
            'messages' => [
                [
                    "role" => "system",
                    "content" => "智能助手"
                ],
                [
                    "role" => "user",
                    "content" => "你好"
                ]
            ],
            'temperature' => 1.0,
            'max_tokens' => 4000,
            'frequency_penalty' => 0,
            'presence_penalty' => 0,
            'stream' => true,
        ], function ($curl, $data) {

            echo $data;

            //设置响应头，确保浏览器正确解析返回的数据流
            if (!headers_sent() && !in_array('content-type', array_map('strtolower', headers_list()))) {
                header('Content-Type: text/event-stream');
                header('Connection: keep-alive');
                // 默认
                header('Cache-Control: no-cache');
                header('Access-Control-Allow-Origin: *');
                header('X-Accel-Buffering: no');
            }

            $prefix = 'data:';
            if (str_starts_with($data, $prefix)) {
                $obj = explode('data: ', $data);
                foreach ($obj as $key => $value) {
                    if ($key == 0) {
                        continue;
                    }
                    $value = json_decode($value,true);
                    if (isset($value['choices'][0]['delta']['content'])) {
                        $this->last .= $value['choices'][0]['delta']['content'];
                    }
                }
            }

            // 判断stream流是否结束
            if (strpos($data, 'DONE')) {
//                $message = Message::where('id', $this->message_id)->find();
//                $message->content = $this->last;
//                $message->save();
            }

            ob_flush();
            flush();
            return strlen($data);
        });
    }


    public function vision()
    {
        $open_ai = new OpenAi('sk-O6LofAEvZHPNh1YP4803FeD69aC64b93B58e30A344A25c66');
        $open_ai->setBaseURL('https://api.ae76.cn');

        // 图片转网站 gpt-4-1106-vision-preview

        $chat = $open_ai->chat([
            'model' => 'gpt-4-vision-preview',
            'messages' => [
                [
                    'role' => 'system',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => '智能助手,帮我回复300字的详情'
                        ]
                    ]
                ],
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'text',
                            'text' => '这张照片里有什么？'
                        ],
                        [
                            'type' => 'image_url',
                            'image_url' => [
                                'url' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg'
                            ]
                        ]
                    ]
                ]
            ],
            'max_tokens' => 4000,
        ]);

        $json = json_decode($chat, true);

        return json($json);
    }

    public function huihua()
    {
        $open_ai = new OpenAi('sk-O6LofAEvZHPNh1YP4803FeD69aC64b93B58e30A344A25c66');
        $open_ai->setBaseURL('https://api.ae76.cn');

        $complete = $open_ai->image([
            "model" => "dall-e-3",
            "prompt" => "帮我画一个小狗",
            "n" => 1,
            "size" => "1024x1024"
        ]);

        $json = json_decode($complete, true);
        return json($json);
    }

    public function test2()
    {
        $sqlFile = root_path() . 'update.sql';
        $sql = file_get_contents($sqlFile);

        $sqlList = $this->parse_sql($sql, 0, ['thinkct_' => config('database.connections.mysql.prefix')]);

        $update_sql_data = Cache::get('update_sql') ?? [];
        foreach($sqlList as $value) {
            try {
                $update_sql = Cache::get('update_sql') ?? [];
                $update_sql_data[] = $value;
                // 跳过已经执行过的sql
                if (in_array($value, $update_sql)) {
                    // 输出提示
                    echo '已经执行过的sql:' . $value . '<br>';
                    continue;
                }
                Db::execute($value);
                echo "执行sql:" . $value . "<br>";
                Cache::set('update_sql1', $update_sql_data);
            } catch(\Exception $e) {
                trace('sql失败语句:' . $value, 'update_error_sql');
            }
        }


        $update_sql = Cache::get('update_sql');
        die(var_dump($update_sql));
    }

    private function parse_sql($sql = '', $limit = 0, $prefix = []): array|string
    {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($prefix)) {
            $to   = current($prefix);
            $from = current(array_flip($prefix));
        }

        if ($sql != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $sql = str_replace(["\r\n", "\r"], "\n", $sql);
            if(empty($sql)) $sql = '';
            $sql = explode("\n", trim($sql));

            // 循环处理每一行
            foreach ($sql as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`'.$from, '`'.$to, $line);
                }
                if ($line == 'BEGIN;' || $line =='COMMIT;') {
                    continue;
                }
                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($limit == 1) {
                return implode("", $pure_sql);
            }

            // 以数组形式返回sql语句\
            $pure_sql = implode(";\n", $pure_sql);
            if(empty($pure_sql)) $pure_sql = '';
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $limit == 1 ? '' : [];
        }
    }
}